import type { LineSeriesOption } from 'echarts/charts'
import { LineChart } from 'echarts/charts'
import type {
  GridComponentOption,
  LegendComponentOption
} from 'echarts/components'
import { GridComponent, LegendComponent } from 'echarts/components'
import type { ComposeOption } from 'echarts/core'
import * as echarts from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react'

import { priceSwitchUnit } from '@/utils/compUtils'
import { roundToNearestMultiple } from '@/utils/echartsUtil'

import type { IDataAnalysisItem, IDataAnalysisType } from '../../data'

type DataAnalysisChartOption = ComposeOption<
  LineSeriesOption | GridComponentOption | LegendComponentOption
>

export interface DataAnalysisProps {
  dataAnalysisList: IDataAnalysisItem[]
  dataAnalysisType: IDataAnalysisType
}

echarts.use([LineChart, GridComponent, LegendComponent, CanvasRenderer])

const DataAnalysis = forwardRef<{ resize: () => void }, DataAnalysisProps>(
  (props, ref) => {
    const chartDomRef = useRef<HTMLDivElement>(null)
    const dataAnalysisChartRef = useRef<any>(null)

    // 视口改变 echarts  -resize
    useImperativeHandle(ref, () => ({
      resize: () => {
        if (dataAnalysisChartRef.current) {
          // console.log("--dataAnalysisChartRef--resize--")
          dataAnalysisChartRef.current.resize()
        }
      }
    }))

    const { dataAnalysisList, dataAnalysisType } = props

    useEffect(() => {
      if (!chartDomRef.current) return
      const finalDataAnalysisList = dataAnalysisList ?? []
      const xAxisData = finalDataAnalysisList.map((dataItem) => {
        const { date } = dataItem
        let newDate = date
        if (
          dataAnalysisType === 'd' ||
          dataAnalysisType === 'half' ||
          dataAnalysisType === 'week'
        ) {
          const dates = date.split('-')
          let dateDay = dates.pop()
          if (dateDay?.charAt(0) === '0') {
            dateDay = dateDay.substring(1)
          }
          newDate = dateDay + '日'
        }

        return newDate
      })

      let yAxisMax = finalDataAnalysisList.reduce(
        (prev: number, curr: IDataAnalysisItem) => {
          const { carNum, personNum, entNum } = curr
          const max = Math.max(carNum, personNum, entNum, prev)
          prev = max
          return prev
        },
        0
      )
      yAxisMax = roundToNearestMultiple(yAxisMax)

      // console.log('--yAxisMax---Math.ceil(yAxisMax / 5)--:', yAxisMax, Math.ceil(yAxisMax / 5));

      const entNumList = finalDataAnalysisList.map(
        (dataItem) => dataItem.entNum ?? 0
      )
      const personNumList = finalDataAnalysisList.map(
        (dataItem) => dataItem.personNum ?? 0
      )
      const carNumList = finalDataAnalysisList.map(
        (dataItem) => dataItem.carNum ?? 0
      )

      const seriesList: LineSeriesOption[] = [
        {
          type: 'line',
          smooth: true,
          lineStyle: {
            width: 1
          },
          symbol: 'none', //折线上对应的data[i]点的标记样式
          data: entNumList,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(64,230,174,0.32)' // 100% 处的颜色
                },
                {
                  offset: 1,
                  color: 'rgba(64,230,174,0)' //   0% 处的颜色
                }
              ],
              global: false // 缺省为 false
            }
          }
        },
        {
          type: 'line',
          smooth: true,
          lineStyle: {
            width: 1
          },
          symbol: 'none',
          data: personNumList,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(59,157,255,0.3)' // 100% 处的颜色
                },
                {
                  offset: 1,
                  color: 'rgba(59,157,255,0)' //   0% 处的颜色
                }
              ],

              global: false // 缺省为 false
            }
          }
        },
        {
          type: 'line',
          smooth: true,
          lineStyle: {
            width: 1
          },
          symbol: 'none',
          data: carNumList,
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(246,110,44,0.32)' // 100% 处的颜色
                },
                {
                  offset: 1,
                  color: 'rgba(246,110,44,0)' //   0% 处的颜色
                }
              ],
              global: false // 缺省为 false
            }
          }
        }
      ]
      if (dataAnalysisChartRef.current) {
        // console.log('--dataAnalysisChartRef.current--存在--');
        dataAnalysisChartRef.current.setOption({
          xAxis: {
            data: xAxisData
          },
          yAxis: {
            type: 'value',
            max: Math.ceil(yAxisMax / 5) * 5,
            interval: Math.ceil(yAxisMax / 5) //计算的坐标轴最大间隔大小
          },
          series: seriesList
        })
      } else {
        const dataAnalysisChart = echarts.init(chartDomRef.current, null, {
          renderer: 'canvas',
          locale: 'ZH'
        })

        const dataAnalysisOptions: DataAnalysisChartOption = {
          color: ['#40E6AE', '#5FA6F5', '#F66E2C'],
          grid: {
            //坐标系
            top: 24,
            right: 52,
            bottom: 48,
            left: 52
          },
          xAxis: {
            // name: '日',
            // nameTextStyle: {
            //   color: '#ffffff',
            // },
            type: 'category',
            data: xAxisData,
            axisTick: { show: false }, //刻度
            axisLine: {
              //轴线
              lineStyle: {
                color: '#404040'
              }
            },
            axisLabel: {
              fontSize: 12,
              color: '#999999'
              // formatter: `{value}${(dataAnalysisType === 'd' || dataAnalysisType === 'half' || dataAnalysisType === 'week') ? '日' : ''}`  //label：会从undefined 到有数据
            },
            boundaryGap: false
          },
          yAxis: {
            type: 'value',
            max: Math.ceil(yAxisMax / 5) * 5,
            interval: Math.ceil(yAxisMax / 5), //计算的坐标轴最间隔大小
            show: true,
            axisLabel: {
              margin: 8,
              color: '#999',
              fontSize: '12px',
              formatter: function (value: number) {
                return priceSwitchUnit(value)
              }
            },
            splitLine: {
              lineStyle: {
                // dashOffset: 10000,
                type: 'dashed',
                color: '#403E3D'
              }
            }
          },
          series: seriesList
        }
        dataAnalysisChart.setOption(dataAnalysisOptions)

        dataAnalysisChartRef.current = dataAnalysisChart
      }
    }, [dataAnalysisList, dataAnalysisType])

    useEffect(() => {
      return () => {
        if (dataAnalysisChartRef.current) {
          dataAnalysisChartRef.current.dispose() //销毁实例
          dataAnalysisChartRef.current = null
        }
      }
    }, [])

    return (
      <div style={{ width: '100%', height: '159px' }} ref={chartDomRef}></div>
    )
  }
)

export default DataAnalysis
